package com.app.happybirds;

import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.app.happybirds.R.id;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity{

	TaskLogin taskLogin;
	ProgressDialog progress;
	EditText editEmail;
	EditText editPass;
	SharedPreferences prefs;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		
		prefs = getSharedPreferences("DataSaved", Context.MODE_PRIVATE);
		
		progress = new ProgressDialog(this);
		progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progress.setMessage("Login... Please wait.");
		
		editEmail = (EditText) findViewById(id.textEMail_login);
		editPass = (EditText) findViewById(id.textPassword_login);
		
		((Button)findViewById(id.buttonGo_login)).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				progress.show();
				if(taskLogin != null)
					taskLogin.cancel(true);
				
				taskLogin = new TaskLogin(hand);
				taskLogin.execute(editEmail.getText().toString(),editPass.getText().toString());
				
			}
		});
		
	}
	
	private Handler hand = new Handler(){
		public void handleMessage(Message msg) {
			
			if (progress.isShowing())
				progress.dismiss();
			
			switch (msg.what) {
			
			case -1:
				Toast.makeText(Login.this, "Error. Please try again... :/ ", Toast.LENGTH_SHORT).show();
				break;
				
			case 1:
				Toast.makeText(Login.this, "OK! :) you are now logged!\nThankyou! :* ", Toast.LENGTH_SHORT).show();
				
				prefs.edit()
				.putString("EmailUser", editEmail.getText().toString())
				.commit();
				startActivity(new Intent(Login.this, Report_Options.class));
				
				finish();
				break;
				
			case 2:
				Toast.makeText(Login.this, (CharSequence) msg.obj, Toast.LENGTH_SHORT).show();
				break;
			}
			
		};
	};
	
	
	class TaskLogin extends AsyncTask<String, String, String>{

		private final Handler handl;

		public TaskLogin(Handler handl) {
			this.handl = handl;
		}
		
		String SHA256(String text)
				throws NoSuchAlgorithmException {

			MessageDigest md = MessageDigest.getInstance("SHA-256");
			byte[] hash = md.digest(text.getBytes());
			StringBuilder sb = new StringBuilder();
			for (byte b : hash) {
				sb.append(String.format("%02x", b));
			}

			return sb.toString();
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			
			if(result == null)
				handl.sendEmptyMessage(-1);
			
			else if (result.equals("OK"))
				handl.sendEmptyMessage(1);
			
			else
				handl.sendMessage(handl.obtainMessage(2, result));
			
			
				
		}
		
		@Override
		protected String doInBackground(String... params) {

			try {
			HttpURLConnection conn = (HttpURLConnection) new URL("http://10.0.2.2/index/xml-login").openConnection();

			String email = params[0];
			String pass = SHA256(params[1]);	
			
			String msg =  URLEncoder.encode("email", "UTF-8")+"="+URLEncoder.encode(email, "UTF-8")+"&"
					+ URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(pass,"UTF-8");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setInstanceFollowRedirects(true);
			
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Host","10.0.2.2");
			conn.setRequestProperty("User-Agent","Android");
			conn.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			conn.setRequestProperty("Accept-Language","en-us,en;q=0.5");
			conn.setRequestProperty("Accept-Encoding","gzip, deflate");
			conn.setRequestProperty("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");
			conn.setRequestProperty("Connection","keep-alive");
			conn.setRequestProperty("Referer","http://birdgameapp.netai.net");
			conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			conn.setRequestProperty("Content-Length",String.valueOf(msg.length()));

			DataOutputStream writer;
			
			writer = new DataOutputStream(conn.getOutputStream());			
			writer.writeBytes(msg);
			writer.flush();
			writer.close();
			
			InputStream input = conn.getInputStream();
			
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(input);
			doc.getDocumentElement().normalize();

			String result = doc.getElementsByTagName("result").item(0).getTextContent().trim();
			
			if (result.equals("true"))
				return "OK";
			
			if(result.equals("false")){
				Element error = (Element) doc.getElementsByTagName("error").item(0);
				String code = error.getElementsByTagName("code").item(0).getTextContent().trim();
				String message = error.getElementsByTagName("message").item(0).getTextContent().trim();
				
				return message;
			}
			
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			} 
			
			return null;
		}
		
	}	
}
